package com.zxc.reggie.service.lmpl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zxc.reggie.common.CustomException;
import com.zxc.reggie.common.R;
import com.zxc.reggie.dto.SetmealDto;
import com.zxc.reggie.entity.Setmeal;
import com.zxc.reggie.entity.SetmealDish;
import com.zxc.reggie.mapper.SetMealMapper;
import com.zxc.reggie.service.SetMealDishService;
import com.zxc.reggie.service.SetMealService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class SetMealServiceImpl extends ServiceImpl<SetMealMapper, Setmeal> implements SetMealService {

    @Resource
    private SetMealDishService setMealDishService;

    @Override
    public R<String> saveWithCategoryName(SetmealDto setmealDto) {


        save(setmealDto);

        List<SetmealDish> setmealDishes = setmealDto.getSetmealDishes();
        setmealDishes = setmealDishes.stream().peek(item -> item.setSetmealId(setmealDto.getId())).collect(Collectors.toList());
        setMealDishService.saveBatch(setmealDishes);
        return R.success("新增成功");
    }

    @Override
    public R<String> removeWithDish(List<Long> ids) {

        LambdaQueryWrapper<Setmeal> setmealLambdaQueryWrapper = new LambdaQueryWrapper<>();
        setmealLambdaQueryWrapper.eq(Setmeal::getId, ids).eq(Setmeal::getStatus, 1);
        int count = count(setmealLambdaQueryWrapper);
        if (count > 0) {
            throw new CustomException("商品在售卖状态不能删除");
        }

        LambdaQueryWrapper<SetmealDish> setmealDishLambdaQueryWrapper = new LambdaQueryWrapper<>();
        setmealDishLambdaQueryWrapper.in(SetmealDish::getSetmealId, ids);
        setMealDishService.remove(setmealDishLambdaQueryWrapper);
        removeByIds(ids);
        return R.success("删除成功");
    }
}
